﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace MishraReader.Windows.Controls
{
    public class WatermarkTextBox : TextBox
    {
        // Using a DependencyProperty as the backing store for Watermark.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty HasTextProperty = DependencyProperty.Register("HasText", typeof(bool), typeof(WatermarkTextBox),
                                                                                                new UIPropertyMetadata(false));

        public static readonly DependencyProperty WatermarkProperty =
            DependencyProperty.Register("Watermark", typeof(String), typeof(WatermarkTextBox), new UIPropertyMetadata(String.Empty));

        private TextBlock _watermark;


        public bool HasText
        {
            get { return (bool)GetValue(HasTextProperty); }
            set { SetValue(HasTextProperty, value); }
        }

        public String Watermark
        {
            get { return (String)GetValue(WatermarkProperty); }
            set { SetValue(WatermarkProperty, value); }
        }

        public override void OnApplyTemplate()
        {
            _watermark = (TextBlock)GetTemplateChild("PART_Watermark");
            UpdateWatermark();

            base.OnApplyTemplate();
        }

        protected override void OnGotFocus(RoutedEventArgs e)
        {
            UpdateWatermark();
            base.OnGotFocus(e);
        }

        protected override void OnLostFocus(RoutedEventArgs e)
        {
            UpdateWatermark();
            base.OnLostFocus(e);
        }

        protected override void OnTextChanged(TextChangedEventArgs e)
        {
            HasText = String.IsNullOrEmpty(Text) == false;

            UpdateWatermark();

            base.OnTextChanged(e);
        }

        private void UpdateWatermark()
        {
            if (_watermark != null)
                _watermark.Visibility = HasText ? Visibility.Collapsed : Visibility.Visible;
        }
    }
}